import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Login from '@/pages/Login.vue';
import NotFound from '@/pages/error/404.vue';
import Threejs from '@/pages/threejs/Threejs.vue';
import IconStore from '@/pages/icon-store/IconStore.vue';
import Layout from '@/layout/Layout.vue';
import { ElMessage } from 'element-plus'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/layout',
        component: Layout,
        children: [
            {
                path: "icon-store",
                name: "图标库",
                component: IconStore,
            },
            {
                path: "threejs",
                name: "3D场景",
                component: Threejs,
            },
            {
                path: '404',
                name: '404',
                component: NotFound
            },
        ]
    },
    {
        path: '/login',
        component: Login
    },
    {
        path: '/:pathMatch(.*)',
        //访问主页的时候 重定向到index页面
        redirect: '/layout/404',
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

/**
 * 全局前置路由守卫，每一次路由跳转前都进入这个 beforeEach 函数
 */
router.beforeEach((to, from, next) => {
    if (to.path == '/login') {
        // 登录或者注册才可以往下进行
        next();
    } else {
        // 获取 token
        const token = localStorage.getItem('Authorization');
        // token 不存在
        if (token === null || token === '') {
            ElMessage.error('您还没有登录，请先登录');
            next('/login');
        } else {
            next();
        }
    }
});

export default router